package com.zhongyu.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
/*
登录
 */
@Controller
@Slf4j
public class LoginController {
    @GetMapping(value = {"/login","/"})
    public  String  login(){

        return "login";
    }
      @PostMapping("/login")
          public  String login(String userCode,String password){
              Subject subject= SecurityUtils.getSubject();
              UsernamePasswordToken token=new UsernamePasswordToken(userCode,password);
              subject.login(token);
              return "redirect:/index";
   }
   @ExceptionHandler({RuntimeException.class})
   public String handleException(RuntimeException ex, Model model){
        String loginErr="";
        if (ex instanceof UnknownAccountException){
            loginErr="用户名或密码错误!";

        }else if(ex instanceof IncorrectCredentialsException){
            loginErr="用户名或密码错误!";
        }else{
            loginErr="系统错误,请联系管理员";
            log.error(loginErr,ex);
        }
        model.addAttribute("loginErr",loginErr);
       return "login";
   }
}
